package com.vmc.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.vmc.exception.VMCException;

public class ErrorPropertiesUtility {

	static Logger logger = LogManager.getLogger(ErrorPropertiesUtility.class);

	private static final String PATH = "errors.properties";
	private static final String ALTERNATE_PATH = "./app/errors/errors.properties";
	private static final String UNKNOWN_ERROR = "Unknown error";
	private static final String RESOURCE_ERROR = "Resource Error";
	private static ErrorPropertiesUtility instance = new ErrorPropertiesUtility();
	private Properties property;
	
	private ErrorPropertiesUtility() {
		
	}
	
	public static ErrorPropertiesUtility getInstance() {
		return instance;
	}
	
	public void load() throws VMCException{
		logger.info("Loading Error Properties...");
		property = new Properties();
		try {
			InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(PATH);
			
			if (inputStream == null) {
				File alternate = new File(ALTERNATE_PATH);
				if (alternate.exists() && alternate.isFile()) {
					inputStream = new FileInputStream(new File(ALTERNATE_PATH));
				}
			}
			
			if (inputStream == null) {
				throw new VMCException(RESOURCE_ERROR);
			}
			property.load(inputStream);
			logger.info(property.toString());
			inputStream.close();
		}
		catch (Exception e) {
			logger.error("Error encountered while loading the Error Properties", e);
			throw new VMCException(e.getMessage());
		}
		logger.info("Loading Error Properties done.");
	}
	
	public Properties getProperty() {
		return property;
	}
	
	public String getError(String code) {
		String error = null;
		
		if (property != null && code != null) {
			error = property.getProperty(code);
			if (error == null || error.isEmpty()) {
				error = code;
			}
		}
		else {
			error = UNKNOWN_ERROR;			
		}
		
		return error;
	}
}
